package cn.b504.qpcr.controller;

import cn.b504.qpcr.entity.AjaxResult;
import cn.b504.qpcr.interfaces.Access;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

@RestController
@RequestMapping("/register")
public class RegisterController {
  private final Access access;

  public RegisterController(Access access) {
    this.access = access;
  }

  /***
   * 上传文件激活,电脑
   * 效果:在classes文件夹里生成以LIC为名的文件,内容和上传文件内容一致,是"key-value"
   * 其中key是SHA1(CPU),value是SHA224(SHA1(CPU))
   *
   * @param file
   * @return
   */
  @RequestMapping("/uploadLIC")   //  (未激活不能使用软件)
  public AjaxResult uploadLIC(MultipartFile file) {
    File f = null;
    try {
      f = File.createTempFile("tmp", null);
      file.transferTo(f);
    } catch (IOException e) {
      e.printStackTrace();
    }
    if (f != null) {
      String line = null;
      InputStream is = null;
      InputStreamReader isr = null;
      BufferedReader br = null;
      try {
        is = new FileInputStream(f);
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        line = br.readLine();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (br != null) {
          try {
            br.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (isr != null) {
          try {
            isr.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (is != null) {
          try {
            is.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (!f.delete()) {
          System.err.println("File delete fail: " + f.getAbsolutePath());
          f.deleteOnExit();
        }
      }
      if (line == null) {
        return AjaxResult.error("", "读取失败");
      }

      File dir;
      try {
        dir = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
        return AjaxResult.error("", "处理失败");
      }

      File lic = new File(dir, "LIC");
      if (lic.exists() && !lic.delete()) {
        System.err.println("File delete fail: software LIC.");
        return AjaxResult.error("", "文件删除失败");
      }
      try {
        if (!lic.createNewFile()) {    // 创建文件
          return AjaxResult.error("", "文件创建失败");
        }
        OutputStream os = new FileOutputStream(lic);
        os.write(line.getBytes());
        os.flush();
        os.close();
        return AjaxResult.ok("", file.getOriginalFilename() + " 处理成功");
      } catch (IOException e) {
        e.printStackTrace();
        return AjaxResult.error("", "文件创建失败");
      }
    }
    return AjaxResult.error("", file.getOriginalFilename() + " 上传失败");
  }

  /**
   * 上传文件批量激活,仪器
   * 上传文件内容:每行对应一台仪器, eg:"key-value"
   * 其中key是仪器ID,value是SHA224(ID)
   * 效果:在license文件夹里生成以key为名,value为内容的文件
   *
   * @param file
   * @return
   */
  @RequestMapping("/uploadLicense")   //   (文件名:仪器序列号:Qxx-xxxx) (文件内容:SHA) (未激活不能连接仪器)
  public AjaxResult uploadLicense(MultipartFile file) {
    File f = null;
    try {
      f = File.createTempFile("tmp", null);
      file.transferTo(f);
    } catch (IOException e) {
      e.printStackTrace();
    }
    if (f != null) {
      List<String> lines = new ArrayList<>();
      InputStream is = null;
      InputStreamReader isr = null;
      BufferedReader br = null;
      try {
        is = new FileInputStream(f);
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
          lines.add(line);
        }
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (br != null) {
          try {
            br.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (isr != null) {
          try {
            isr.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (is != null) {
          try {
            is.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (!f.delete()) {
          System.err.println("File delete fail: " + f.getAbsolutePath());
          f.deleteOnExit();
        }
      }
      if (lines.size() == 0) {
        return AjaxResult.error("", "读取失败");
      }

      File dir;
      try {
        dir = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
        return AjaxResult.error("", "处理失败");
      }
      dir = new File(dir, "licenses");
      if (!dir.exists() && !dir.mkdirs()) {
        return AjaxResult.error("", "创建文件夹失败");
      }
      if (!dir.isDirectory() && (!dir.delete() || !dir.mkdirs())) {
        return AjaxResult.error("", "删除文件失败");
      }
      for (String line : lines) {
        String[] arr = line.split("-");
        if (arr.length >= 2) {
          StringJoiner joiner = new StringJoiner("-");
          for (int i = 0; i < arr.length - 1; i++) {
            joiner.add(arr[i]);
          }
          File fileLic = new File(dir, joiner.toString());
          if (fileLic.exists() && !fileLic.delete()) {
            System.err.println("File delete fail: software LIC.");
            return AjaxResult.error("", "文件删除失败");
          }
          try {
            if (!fileLic.createNewFile()) {    // 创建文件
              return AjaxResult.error("", "文件创建失败");
            }
            OutputStream os = new FileOutputStream(fileLic);
            os.write(arr[arr.length - 1].getBytes());
            os.flush();
            os.close();
          } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("", "文件创建失败");
          }
        }
      }
      return AjaxResult.ok("", file.getOriginalFilename() + " 处理成功");
    }
    return AjaxResult.error("", file.getOriginalFilename() + " 上传失败");
  }

  @RequestMapping("/check")
  public AjaxResult check() {
    if (access.check()) {
      return AjaxResult.ok(null);
    }
    return AjaxResult.error(null);
  }
}
